package com.yoomiito.app.ui.yijiayou

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import com.gyf.barlibrary.ImmersionBar
import com.jakewharton.rxbinding3.widget.textChanges
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.distanceFormat
import com.yoomiito.app.model.LatLng
import com.yoomiito.app.model.SearchTip
import com.yoomiito.app.model.oil.OilStationData
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.gasstation.GasSortTabView
import com.yoomiito.app.ui.anyview.gasstation.RcyView
import com.yoomiito.app.ui.anyview.gasstation.SearchHistoryView
import com.yoomiito.app.utils.Const
import com.yoomiito.app.utils.DensityUtil
import com.yoomiito.app.utils.GPSConverterUtils
import com.yoomiito.app.utils.ResUtil
import com.yoomiito.app.widget.state.EmptyType_3
import kotlinx.android.synthetic.main.act_gas_station_search.*
import kotlinx.android.synthetic.main.item_search.*
import kotlinx.android.synthetic.main.item_search_toolbar.*


class GasStationSearchActivity : BaseGasStationActivity<GasStationSearchPresenter>() {
    companion object {
        const val GasStationSearchHistory = "gas_station_search_history"
        const val DestinationTab = 1 //目的地搜索
        const val StationTab = 2 //油站搜索
        fun start(context: Context, latlng: LatLng) {
            val intent = Intent(context, GasStationSearchActivity::class.java)
            intent.putExtra(Const.Common.Data, latlng)
            context.startActivity(intent)
        }
    }

    private lateinit var latlng: LatLng
    private lateinit var currentLatLng: LatLng
    private val destinationAdapter = DistantionAdapter(null).also {//目的地
        it.setOnItemClickListener { adapter, view, position ->
            //按照目的地搜索油站 传目的地的经纬度
            val tip = it.data[position]
            currentLatLng = LatLng(tip.latlng.lat, tip.latlng.lng)
            showLoading()
            toSearchStation()
        }
    }
    private val stationListAdapter = GasStationListAdapter(null).also {//油站
        it.setOnItemClickListener { adapter, view, position ->
//            DebounceHelper.click(1).compose(bindToLifecycle()).subscribe {_->
                val data = it.data[position]
                showLoading()
                if (data.type == 1) { //易加油 经纬度需转换为百度经纬度
                    val gps = GPSConverterUtils.gcj02_To_Bd09(latlng.lat, latlng.lng)
                    oilDetail(data.gasId, latlng, LatLng(gps.lat, gps.lon), data.type)
                } else {
                    //团油、小桔为高德经纬度
                    oilDetail(data.gasId, latlng, latlng, data.type)
                }
            }
//        }
        it.setOnItemChildClickListener { adapter, view, position ->
            val data = it.data[position] as OilStationData
            /*
            易加油 type=1 坐标为百度坐标
            团油 type=2 坐标为火星坐标系
            小桔 type=3 坐标为火星坐标系
             */
            if (data.type==1){
//                val converter = CoordinateConverter()
//                // CoordType.GPS 待转换坐标类型
//                converter.from(CoordinateConverter.CoordType.BAIDU)
//                // sourceLatLng待转换坐标点 LatLng类型
//                converter.coord(com.amap.api.maps2d.model.LatLng(data.lat.toDouble(),data.lng.toDouble()))
//                // 执行转换操作
//                val latlng:com.amap.api.maps2d.model.LatLng = converter.convert()
//                showSelectMap(latlng.latitude,latlng.longitude)
            }else{
                showSelectMap(data.lat.toDouble(),data.lng.toDouble())
            }
        }
    }
    private lateinit var destinationView: RcyView
    private lateinit var stationListView: RcyView
    private lateinit var searchView: SearchHistoryView
    private var currentTab = DestinationTab
    private var mCurrentPage = 1
    private val tips = mutableListOf<SearchTip>()
    private var mCurrentKeyWord = ""
    private var sortType = GasSortTabView.DistanceSort //默认距离优先

    override fun getLayoutId(): Int = R.layout.act_gas_station_search

    override fun newP(): GasStationSearchPresenter = GasStationSearchPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        latlng = intent.getParcelableExtra(Const.Common.Data)
        setWindowStatusBarColor(R.color.color_F4F4F4)
        act_search_back.setOnClickListener { finish() }
        item_search_et.hint = "请输入要搜索的目的地"
        act_search_search.setOnClickListener {
            val keyword = item_search_et.text.toString().trim()
            if (keyword.isEmpty()){
                "请输入搜索关键字".showToast()
                return@setOnClickListener
            }
            mCurrentKeyWord = keyword
            mCurrentPage = 1
            showLoading()
            toSearchKeyWord()
            searchView.saveHistory(keyword)
        }

        item_search_del.setOnClickListener {
            item_search_et.setText("")
            tips.clear()
            destinationAdapter.notifyDataSetChanged()
            sortTab.visibility = View.GONE
            showSearchView()
        }

        initView()
        initTab()
        val m12 = DensityUtil.dp2px(12f)

        frameLayout.addView(stationListView.getView(), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT).also {
            it.setMargins(m12, m12, m12, m12)
        })
        frameLayout.addView(destinationView.getView(), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT).also {
            it.setMargins(m12, m12, m12, m12)
        })
        frameLayout.addView(searchView.view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).also {
            it.setMargins(m12, m12, m12, m12)
        })

        val shadeView = View(this)
        shadeView.setBackgroundResource(R.color.color_black_80)
        shadeView.visibility = View.GONE
        frameLayout.addView(shadeView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        sortTab.init(shadeView, false)
        sortTab.onResultListener = {
            when (it) {
                -1 -> {//不处理
                }
                GasSortTabView.DistanceSort -> {
                    sortType = GasSortTabView.DistanceSort
                    stationListAdapter.data.sortBy { sort -> sort.distance }
                    stationListAdapter.notifyDataSetChanged()
                    stationListView.scrollTop()
                }//距离优先
                GasSortTabView.PriceSort -> {
                    sortType = GasSortTabView.PriceSort
                    stationListAdapter.data.sortBy { sort -> sort.price }
                    stationListAdapter.notifyDataSetChanged()
                    stationListView.scrollTop()
                }//价格优先
                else -> {
                    oilNum = it
                    mCurrentPage = 1
                    showLoading()
                    toSearchStation()
                }
            }
        }
        showSearchView()
        item_search_et.textChanges().subscribe{ charSequence: CharSequence ->
            if (charSequence.isEmpty()){
                tips.clear()
                sortTab.visibility = View.GONE
                showSearchView()
            }
        }
        item_search_et.postDelayed({
            // item_search_et.isFocusable = true
            // item_search_et.isFocusableInTouchMode = true
            item_search_et.requestFocus()
            val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(item_search_et, 0)
        },100)
    }

    //设置Activity对应的顶部状态栏的颜色
    private fun setWindowStatusBarColor(colorResId: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = ResUtil.getColor(colorResId)
        }
    }

    public override fun initImmersionBar() {
        ImmersionBar.with(this).keyboardEnable(false).init()
    }

    private fun initTab() {
        tabLayout.addTab(tabLayout.newTab().setText("目的地").setTag(DestinationTab))
        tabLayout.addTab(tabLayout.newTab().setText("加油站").setTag(StationTab))
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                currentTab = p0?.tag as Int
                sortTab.visibility = View.GONE
                mCurrentPage = 1
                item_search_et.setText("")
                mCurrentKeyWord = ""
                item_search_et.hint = when(currentTab){
                    DestinationTab->"请输入要搜索的目的地"
                    StationTab -> "请输入要搜索的加油站名称"
                    else-> ""
                }
//                oilNum = GasSortTabView.DefaultOilNum
                currentLatLng = latlng
//                sortTab.reset()
                showSearchView()
            }
        })
    }

    private fun initView() {
        destinationView = RcyView(this, false,"未找到目的地\n请更改搜索关键词").also {
            it.setAdapter(destinationAdapter)
        }
        stationListView = RcyView(this, true,"未找到油站\n尝试更改下筛选条件").also {
            it.setAdapter(stationListAdapter)
            it.onLoadMoreListener = {
                //上拉刷新
                mCurrentPage++
                toSearchStation()
            }
        }
        searchView = SearchHistoryView(this).also {
            it.init(GasStationSearchHistory)
            it.onTagClickListener = { keyword ->
                mCurrentPage = 1
                mCurrentKeyWord = keyword
                showLoading()
                toSearchKeyWord()
            }
        }
    }

    private fun toSearchStation() {
        sortTab.visibility = View.VISIBLE
        p.searchGasStation(oilNum,currentLatLng,currentTab.toString(),mCurrentKeyWord,mCurrentPage)
    }

    //
    private fun toSearchKeyWord() {
        item_search_et.setText(mCurrentKeyWord)
        when (currentTab) {
            DestinationTab -> {
                search(mCurrentKeyWord)
            }
            StationTab -> {
                currentLatLng = latlng
                toSearchStation()
            }
        }
    }

    fun setData(data: MutableList<OilStationData>?) {
        dismissLoading()
        if (data.isNullOrEmpty()) {
            if (mCurrentPage==1){
                stationListAdapter.setNewData(arrayListOf<OilStationData>())
                stationListView.showEmpty(EmptyType_3::class.java)
                showStationListView(true)
            }else{
                stationListView.finishLoadMoreWithNoMoreData()
            }
        } else {
            when(sortType){
                GasSortTabView.DistanceSort->{
                    data?.sortBy { sort -> sort.distance }
                }
                GasSortTabView.PriceSort->{
                    data?.sortBy { sort -> sort.price }
                }
            }
            showStationListView(false)
            if (mCurrentPage == 1) {
                stationListAdapter.setNewData(data)
                stationListView.showContent()
                stationListView.setNoMoreData(false)
            } else {
                stationListAdapter.addData(data)
            }
            stationListView.finishLoadMore()
        }
    }

    private fun search(keyword: String) {
//        val inputquery = InputtipsQuery(keyword, "")
//        val inputTips = Inputtips(this, inputquery)
//        inputTips.setInputtipsListener { p0, p1 ->
//            tips.clear()
//            dismissLoading()
//            if (p1 == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
//                if (p0==null||p0.size==0){
//                    showDestinationView(true)
//                }else{
//                    p0.forEach {
//                        if (it.point != null) {
//                            val dis = AMapUtils.calculateLineDistance(com.amap.api.maps2d.model.LatLng(it.point.latitude, it.point.longitude), com.amap.api.maps2d.model.LatLng(latlng.lat, latlng.lng))
//                            val d = "${dis.distanceFormat()}"
//                            tips.add(SearchTip(it.name, it.district + it.address, LatLng(it.point.latitude, it.point.longitude), d))
//                        }
//                    }
//                    destinationAdapter.setNewData(tips)
//                    showDestinationView(false)
//                }
//            } else {
//                showDestinationView(true)
//            }
//        }
//        inputTips.requestInputtipsAsyn()
    }

    private fun showStationListView(empty: Boolean) {
        searchView.show(false)
        destinationView.show(show = false, empty = false)
        stationListView.show(true, empty)
    }

    private fun showDestinationView(empty: Boolean) {
        searchView.show(false)
        destinationView.show(true, empty)
        stationListView.show(show = false, empty = false)
    }

    private fun showSearchView() {
        searchView.show(true)
        destinationView.show(false, empty = false)
        stationListView.show(false, empty = false)
    }

    fun showError(){
        stationListView.finishLoadMore()
        if (mCurrentPage==1){
            searchView.show(false)
            destinationView.show(show = false, empty = false)
            stationListView.show(true, empty = false)
            stationListView.showError()
        }else{
            "数据请求超时，请稍后再试".showToast()
        }
    }

    override fun onStop() {
        super.onStop()
        dismissLoading()
        val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(item_search_et.windowToken, 0)
    }
}